home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / pprint.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  11.6 KB  |  351 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. """Support to pretty-print lists, tuples, & dictionaries recursively.
  5.  
  6. Very simple, but useful, especially in debugging data structures.
  7.  
  8. Classes
  9. -------
  10.  
  11. PrettyPrinter()
  12.     Handle pretty-printing operations onto a stream using a configured
  13.     set of formatting parameters.
  14.  
  15. Functions
  16. ---------
  17.  
  18. pformat()
  19.     Format a Python object into a pretty-printed representation.
  20.  
  21. pprint()
  22.     Pretty-print a Python object to a stream [default is sys.sydout].
  23.  
  24. saferepr()
  25.     Generate a 'standard' repr()-like value, but protect against recursive
  26.     data structures.
  27.  
  28. """
  29. import sys as _sys
  30. from cStringIO import StringIO as _StringIO
  31. __all__ = [
  32.     'pprint',
  33.     'pformat',
  34.     'isreadable',
  35.     'isrecursive',
  36.     'saferepr',
  37.     'PrettyPrinter']
  38. _commajoin = ', '.join
  39. _id = id
  40. _len = len
  41. _type = type
  42.  
  43. def pprint(object, stream = None):
  44.     '''Pretty-print a Python object to a stream [default is sys.sydout].'''
  45.     printer = PrettyPrinter(stream = stream)
  46.     printer.pprint(object)
  47.  
  48.  
  49. def pformat(object):
  50.     '''Format a Python object into a pretty-printed representation.'''
  51.     return PrettyPrinter().pformat(object)
  52.  
  53.  
  54. def saferepr(object):
  55.     '''Version of repr() which can handle recursive data structures.'''
  56.     return _safe_repr(object, { }, None, 0)[0]
  57.  
  58.  
  59. def isreadable(object):
  60.     '''Determine if saferepr(object) is readable by eval().'''
  61.     return _safe_repr(object, { }, None, 0)[1]
  62.  
  63.  
  64. def isrecursive(object):
  65.     '''Determine if object requires a recursive representation.'''
  66.     return _safe_repr(object, { }, None, 0)[2]
  67.  
  68.  
  69. class PrettyPrinter:
  70.     
  71.     def __init__(self, indent = 1, width = 80, depth = None, stream = None):
  72.         '''Handle pretty printing operations onto a stream using a set of
  73.         configured parameters.
  74.  
  75.         indent
  76.             Number of spaces to indent for each level of nesting.
  77.  
  78.         width
  79.             Attempted maximum number of columns in the output.
  80.  
  81.         depth
  82.             The maximum depth to print out nested structures.
  83.  
  84.         stream
  85.             The desired output stream.  If omitted (or false), the standard
  86.             output stream available at construction will be used.
  87.  
  88.         '''
  89.         indent = int(indent)
  90.         width = int(width)
  91.         if not indent >= 0:
  92.             raise AssertionError
  93.         if not depth is None or depth > 0:
  94.             raise AssertionError, 'depth must be > 0'
  95.         if not width:
  96.             raise AssertionError
  97.         self._depth = depth
  98.         self._indent_per_level = indent
  99.         self._width = width
  100.         if stream is not None:
  101.             self._stream = stream
  102.         else:
  103.             self._stream = _sys.stdout
  104.  
  105.     
  106.     def pprint(self, object):
  107.         self._stream.write(self.pformat(object) + '\n')
  108.  
  109.     
  110.     def pformat(self, object):
  111.         sio = _StringIO()
  112.         self._format(object, sio, 0, 0, { }, 0)
  113.         return sio.getvalue()
  114.  
  115.     
  116.     def isrecursive(self, object):
  117.         return self.format(object, { }, 0, 0)[2]
  118.  
  119.     
  120.     def isreadable(self, object):
  121.         (s, readable, recursive) = self.format(object, { }, 0, 0)
  122.         if readable:
  123.             pass
  124.         return not recursive
  125.  
  126.     
  127.     def _format(self, object, stream, indent, allowance, context, level):
  128.         level = level + 1
  129.         objid = _id(object)
  130.         if objid in context:
  131.             stream.write(_recursion(object))
  132.             self._recursive = True
  133.             self._readable = False
  134.             return None
  135.         
  136.         rep = self._repr(object, context, level - 1)
  137.         typ = _type(object)
  138.         sepLines = _len(rep) > self._width - 1 - indent - allowance
  139.         write = stream.write
  140.         if sepLines:
  141.             if typ is dict:
  142.                 write('{')
  143.                 if self._indent_per_level > 1:
  144.                     write((self._indent_per_level - 1) * ' ')
  145.                 
  146.                 length = _len(object)
  147.                 if length:
  148.                     context[objid] = 1
  149.                     indent = indent + self._indent_per_level
  150.                     items = object.items()
  151.                     items.sort()
  152.                     (key, ent) = items[0]
  153.                     rep = self._repr(key, context, level)
  154.                     write(rep)
  155.                     write(': ')
  156.                     self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level)
  157.                     if length > 1:
  158.                         for key, ent in items[1:]:
  159.                             rep = self._repr(key, context, level)
  160.                             write(',\n%s%s: ' % (' ' * indent, rep))
  161.                             self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level)
  162.                         
  163.                     
  164.                     indent = indent - self._indent_per_level
  165.                     del context[objid]
  166.                 
  167.                 write('}')
  168.                 return None
  169.             
  170.             if typ is list or typ is tuple:
  171.                 if typ is list:
  172.                     write('[')
  173.                     endchar = ']'
  174.                 else:
  175.                     write('(')
  176.                     endchar = ')'
  177.                 if self._indent_per_level > 1:
  178.                     write((self._indent_per_level - 1) * ' ')
  179.                 
  180.                 length = _len(object)
  181.                 if length:
  182.                     context[objid] = 1
  183.                     indent = indent + self._indent_per_level
  184.                     self._format(object[0], stream, indent, allowance + 1, context, level)
  185.                     if length > 1:
  186.                         for ent in object[1:]:
  187.                             write(',\n' + ' ' * indent)
  188.                             self._format(ent, stream, indent, allowance + 1, context, level)
  189.                         
  190.                     
  191.                     indent = indent - self._indent_per_level
  192.                     del context[objid]
  193.                 
  194.                 if typ is tuple and length == 1:
  195.                     write(',')
  196.                 
  197.                 write(endchar)
  198.                 return None
  199.             
  200.         
  201.         write(rep)
  202.  
  203.     
  204.     def _repr(self, object, context, level):
  205.         (repr, readable, recursive) = self.format(object, context.copy(), self._depth, level)
  206.         if not readable:
  207.             self._readable = False
  208.         
  209.         if recursive:
  210.             self._recursive = True
  211.         
  212.         return repr
  213.  
  214.     
  215.     def format(self, object, context, maxlevels, level):
  216.         """Format object for a specific context, returning a string
  217.         and flags indicating whether the representation is 'readable'
  218.         and whether the object represents a recursive construct.
  219.         """
  220.         return _safe_repr(object, context, maxlevels, level)
  221.  
  222.  
  223.  
  224. def _safe_repr(object, context, maxlevels, level):
  225.     typ = _type(object)
  226.     if typ is str:
  227.         if 'locale' not in _sys.modules:
  228.             return (`object`, True, False)
  229.         
  230.         if "'" in object and '"' not in object:
  231.             closure = '"'
  232.             quotes = {
  233.                 '"': '\\"' }
  234.         else:
  235.             closure = "'"
  236.             quotes = {
  237.                 "'": "\\'" }
  238.         qget = quotes.get
  239.         sio = _StringIO()
  240.         write = sio.write
  241.         for char in object:
  242.             if char.isalpha():
  243.                 write(char)
  244.                 continue
  245.             write(qget(char, `char`[1:-1]))
  246.         
  247.         return ('%s%s%s' % (closure, sio.getvalue(), closure), True, False)
  248.     
  249.     if typ is dict:
  250.         if not object:
  251.             return ('{}', True, False)
  252.         
  253.         objid = _id(object)
  254.         if maxlevels and level > maxlevels:
  255.             return ('{...}', False, objid in context)
  256.         
  257.         if objid in context:
  258.             return (_recursion(object), False, True)
  259.         
  260.         context[objid] = 1
  261.         readable = True
  262.         recursive = False
  263.         components = []
  264.         append = components.append
  265.         level += 1
  266.         saferepr = _safe_repr
  267.         for k, v in object.iteritems():
  268.             (krepr, kreadable, krecur) = saferepr(k, context, maxlevels, level)
  269.             (vrepr, vreadable, vrecur) = saferepr(v, context, maxlevels, level)
  270.             append('%s: %s' % (krepr, vrepr))
  271.             if readable and kreadable:
  272.                 pass
  273.             readable = vreadable
  274.             if krecur or vrecur:
  275.                 recursive = True
  276.                 continue
  277.         
  278.         del context[objid]
  279.         return ('{%s}' % _commajoin(components), readable, recursive)
  280.     
  281.     if typ is list or typ is tuple:
  282.         if typ is list:
  283.             if not object:
  284.                 return ('[]', True, False)
  285.             
  286.             format = '[%s]'
  287.         elif _len(object) == 1:
  288.             format = '(%s,)'
  289.         elif not object:
  290.             return ('()', True, False)
  291.         
  292.         format = '(%s)'
  293.         objid = _id(object)
  294.         if maxlevels and level > maxlevels:
  295.             return (format % '...', False, objid in context)
  296.         
  297.         if objid in context:
  298.             return (_recursion(object), False, True)
  299.         
  300.         context[objid] = 1
  301.         readable = True
  302.         recursive = False
  303.         components = []
  304.         append = components.append
  305.         level += 1
  306.         for o in object:
  307.             (orepr, oreadable, orecur) = _safe_repr(o, context, maxlevels, level)
  308.             append(orepr)
  309.             if not oreadable:
  310.                 readable = False
  311.             
  312.             if orecur:
  313.                 recursive = True
  314.                 continue
  315.         
  316.         del context[objid]
  317.         return (format % _commajoin(components), readable, recursive)
  318.     
  319.     rep = `object`
  320.     if rep:
  321.         pass
  322.     return (rep, not rep.startswith('<'), False)
  323.  
  324.  
  325. def _recursion(object):
  326.     return '<Recursion on %s with id=%s>' % (_type(object).__name__, _id(object))
  327.  
  328.  
  329. def _perfcheck(object = None):
  330.     import time
  331.     if object is None:
  332.         object = [
  333.             ('string', (1, 2), [
  334.                 3,
  335.                 4], {
  336.                 5: 6,
  337.                 7: 8 })] * 100000
  338.     
  339.     p = PrettyPrinter()
  340.     t1 = time.time()
  341.     _safe_repr(object, { }, None, 0)
  342.     t2 = time.time()
  343.     p.pformat(object)
  344.     t3 = time.time()
  345.     print '_safe_repr:', t2 - t1
  346.     print 'pformat:', t3 - t2
  347.  
  348. if __name__ == '__main__':
  349.     _perfcheck()
  350.  
  351.